﻿using System;
using System.Web;
using NLog;

namespace Medianamik.Core.Logging
{
    [Filter("emailFilter")]
    public class EmailFilter : Filter
    {
        protected override FilterResult Check(LogEventInfo logEvent)
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Application["SentInLastMinute"] != null)
                {
                    var lastError = (DateTime) HttpContext.Current.Application["LastError"];
                    var diff = DateTime.Now.Subtract(lastError);

                    if (diff.Minutes < 20)
                    {
                        var numberOfMessage = (int) HttpContext.Current.Application["SentInLastMinute"];
                        numberOfMessage++;
                        HttpContext.Current.Application["SentInLastMinute"] = numberOfMessage;

                        if (numberOfMessage > 10)
                        {
                            return numberOfMessage%1000 == 0
                                       ? FilterResult.Neutral
                                       : FilterResult.Ignore;
                        }

                        return FilterResult.Neutral;
                    }

                    HttpContext.Current.Application["SentInLastMinute"] = 1;
                    HttpContext.Current.Application["LastError"] = DateTime.Now;

                    return FilterResult.Neutral;
                }

                HttpContext.Current.Application.Add("SentInLastMinute", 1);
                HttpContext.Current.Application.Add("LastError", DateTime.Now);
            }

            return FilterResult.Neutral;
        }
    }
}
